package com.bootlever.framework.core.template;

import com.alibaba.fastjson.JSON;
import com.bootlever.framework.common.constant.EnumMailType;
import com.bootlever.framework.common.model.BaseMailEntity;
import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.core.properties.BasicProperties;
import com.bootlever.framework.core.properties.basic.MailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailTemplate {

    private static final Logger logger = LoggerFactory.getLogger(MailTemplate.class);

    private String smtpHost;
    private String smtpPort;
    private String password;
    private String nickName;
    private String user;
    private Session mailSession;
    private InternetAddress fromAddress;

    private static final String MAIL_SMTP_AUTH = "mail.smtp.auth";
    private static final String MAIL_SMTP_HOST = "mail.smtp.host";
    private static final String MAIL_SMTP_PORT = "mail.smtp.port";
    private static final String MAIL_USER = "mail.user";
    private static final String MAIL_PASSWORD = "mail.password";

    public boolean init(BasicProperties basicProperties) throws AddressException {
        if (basicProperties == null) {
            throw new IllegalArgumentException("base properties can't be null");
        }
        if (basicProperties.getMail()==null || !basicProperties.getMail().isEnable()) {
            return false;
        }
        MailSender mail = basicProperties.getMail();
        final Properties properties = new Properties();
        properties.put(MAIL_SMTP_AUTH,true);
        smtpHost = mail.getSmtpHost();
        properties.put(MAIL_SMTP_HOST, smtpHost);
        smtpPort = mail.getSmtpPort();
        properties.put(MAIL_SMTP_PORT,smtpPort);
        user = mail.getFromAddress();
        properties.put(MAIL_USER, user);
        password = mail.getPassword();
        properties.put(MAIL_PASSWORD, password);
        nickName = StringUtils.getNString(mail.getNickName());
        //身份认证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
        mailSession = Session.getInstance(properties,authenticator);
        fromAddress = new InternetAddress(nickName + "<"
        + mail.getFromAddress()+">");
        return true;
    }

    public void send(BaseMailEntity mailEntity) throws MessagingException {
        if (mailEntity == null || !mailEntity.isEnableSend()) {
            //邮件为空，或者内容中有为空的
            throw new IllegalArgumentException("mail entity can't be null or disabled");
        }
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(fromAddress);
        message.setSubject(mailEntity.getTitle());
        if (EnumMailType.HTML.getContentType().equals(mailEntity.getContentType())){
            message.setContent(mailEntity.getContent(), mailEntity.getContentType());
        } else {
            message.setText(mailEntity.getContent());
        }
        for (String target : mailEntity.getReceivers()) {
            try {
                InternetAddress to = new InternetAddress(target);
                message.setRecipient(Message.RecipientType.TO, to);
                Transport.send(message);
                if (logger.isInfoEnabled()) {
                    logger.info("[发送邮件{}", JSON.toJSON(message)+"]");
                }
            } catch (Exception e) {
                logger.error("[发送给{}的邮件发送异常，原因:{}]", target, e);
            }
        }
    }

    public String getSmtpHost() {
        return smtpHost;
    }

    public String getSmtpPort() {
        return smtpPort;
    }

    public String getPassword() {
        return password;
    }

    public String getNickName() {
        return nickName;
    }

    public String getUser() {
        return user;
    }

    public Session getMailSession() {
        return mailSession;
    }

    public InternetAddress getFromAddress() {
        return fromAddress;
    }
}
